<?php

namespace app\api\controller;

use app\api\model\User;
use app\api\service\Token;
use app\api\validate\User as ValidateUser;
use app\BaseController;
use app\common\LogService;
use think\exception\ValidateException;

class Login extends BaseController
{
    public function index()
    {
        $param = input('post.');
        $config = getConfig('admin','sys_main');
        if ($config['log_switch'] != 1) return error('当前App已关闭登录');
        $recordLog = function ($status, $message = '') {
            LogService::record(
                name: '用户登录',
                user_id: getUid(),
                status: $status,
                content: $message == '' ? [] : ['reason' => $message],
            );
        };
        try {
            validate(ValidateUser::class)->scene('login')->check($param);
            $isEmpty = User::where('qq', $param['qq']);
            if ($isEmpty->findOrEmpty()->isEmpty()) {
                $recordLog(0, '账号不存在');
                return error('账号不存在');
            }
            $user = $isEmpty->find();
            if (md5($param['password'] . config('secure.secure_salt')) != $user['password']) return error('账号或密码错误');
            if ($user['status'] == 0) {
                $recordLog(0, '账号待审核');
                return error('账号待审核，请稍后再尝试');
            }
            if ($user['status'] == 2) {
                $recordLog(0, '账号已被封禁');
                return error('账号已被封禁');
            }
            $data = [
                'id' => $user['id'],
                'role' => $user['role'],
                'nickname' => $user['nickname'],
                'avator' => $user['avator'],
                'expire_time' => time() +  config('secure.expire_time')
            ];
            $token = (new Token)->getToken($data);
            if (!$token) {
                $recordLog(0, 'Token值生成失败');
                return error('登录失败');
            }
            User::where('id', $user['id'])->update(['last_login_ip' => getIP(), 'last_time' => time()]);
            // 执行签到
            $recordLog(1);
            return success(['token' => $token]);
        } catch (ValidateException $e) {
            $recordLog(0, $e->getError());
            return error($e->getError(), 201);
        }
    }
    public function logout()
    {
        $token = input('token') ?? request()->header('token');
        if (!$token) return error('Token不能为空', 201);
        if (cache($token)) {
            LogService::record(
                user_id: getUid(),
                name: '退出登录',
            );
            cache($token, null);
            return success();
        }
    }
}
